package com.stark.wechat.service.impl.message.template;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.stark.wechat.domain.Template;
import com.stark.wechat.enums.Status;
import com.stark.wechat.message.template.TemplateField;
import com.stark.wechat.message.template.TemplateMessage;
import com.stark.wechat.service.impl.TemplateServiceImpl;
import com.stark.wechat.service.message.template.PushTemplateMessageService;
import com.stark.wechat.util.DateUtil;

/**
 * 推送模板消息测试。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0, 2017/8/6
 */
@Service("pushTestService")
public class PushTestServiceImpl implements PushTemplateMessageService {
	/**
	 * 模板名称
	 */
	public static final String TEMPLATE_NAME = "测试推送模板消息";

	@Autowired
	private TemplateServiceImpl templateService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<TemplateMessage> generateTemplateMessages() {
		// 查询模板ID
		Template template = this.templateService.getByName(TEMPLATE_NAME);
		if (template == null) {
			return new ArrayList<TemplateMessage>();
		}
		// 查询案件信息
		String sql = "select OPEN_ID, SUBSCRIBE_TIME"
				+ " from wechat_user"
				+ " where STATUS = " + Status.ENABLE.getValue() + " and not exists (select 1 from wechat_message_push"
				+ " where ELIMINITION = concat(wechat_user.OPEN_ID, '-', date_format(wechat_user.SUBSCRIBE_TIME, '%Y%m%d%H%i%s')))"
				+ " order by SUBSCRIBE_TIME";
		List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);
		
		List<TemplateMessage> msgList = new ArrayList<>();
		TemplateMessage msg;
		for (Map<String, Object> item : list) {
			msg = this.getTemplateMessage(item);
			msg.setTemplate_id(template.getTemplateId());
			msgList.add(msg);
		}
		return msgList;
	}
	
	private TemplateMessage getTemplateMessage(Map<String, Object> item) {
		String openId = (String) item.get("OPEN_ID");
		Date subscribeTime = (Date) item.get("SUBSCRIBE_TIME");
		
		Map<String, TemplateField> data = new HashMap<>();
		// first
		data.put("first", new TemplateField("欢迎关注公众号"));
		// 关注时间
		try {
			data.put("keyword1", new TemplateField(DateUtil.format(subscribeTime, DateUtil.DATETIME)));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		// remark
		data.put("remark", new TemplateField("点击详情跳转百度"));
		
		TemplateMessage msg = new TemplateMessage();
		msg.setTouser(openId);
		msg.setData(data);
		msg.setEliminition(openId + "-" + DateUtil.format(subscribeTime, "yyyyMMddHHmmss"));
		msg.setTemplateName(TEMPLATE_NAME);
		msg.setUrl("https://www.baidu.com/");
		return msg;
	}
}
